<template>
  <div class="employees-container">
    <div class="app-container">

      <page-tools>
        <template #left>
          <span>总记录数:{{ total }}条</span>
        </template>

        <template #right>
          <el-button type="primary" size="small" @click="$router.push('./import?type=user')">excel导入</el-button>
          <el-button type="primary" size="small" @click="clickExport">excel导出</el-button>
          <el-button type="primary" size="small" @click="showDialog = true">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table v-loading="loading" :data="list" border>
          <el-table-column type="index" :index="indexMethod" label="序号" sortable="" />
          <el-table-column prop="username" label="姓名" sortable="" />
          <el-table-column label="手机号" sortable="" prop="mobile" />
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column :formatter="formatEmployment" label="聘用形式" sortable="" prop="formOfEmployment" />
          <el-table-column label="部门" sortable="" prop="departmentName" />

          <el-table-column label="入职时间" sortable="">
            <template #default="{row}">
              {{ row.timeOfEntry | formatTime }}
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`./employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="showRoleFn(row.id)">角色</el-button>
              <el-button type="text" size="small" :disabled="!checkPermission('DELETE_BTN')" @click="delEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <div style="height: 60px; margin-top: 10px">
          <el-pagination
            :total="total"
            :current-page="page"
            :page-size="size"
            layout="total, sizes, prev, pager, next, jumper"
            :page-sizes="[2, 4, 6, 8]"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
      <AddEmployee :show-dialog.sync="showDialog" @addEmployee="getEmployeeList" />
      <AssignRole :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
    </div>
  </div>
</template>

<script>
import { reqGetEmployeeList, reqDelEmployee } from '@/api/employees'
import EmployeeEnum from '@/api/constant/employees'
import AddEmployee from './components/add-employee'
import AssignRole from './components/assign-role'
import dayjs from 'dayjs'
export default {
  name: 'Employees',
  components: {
    AddEmployee,
    AssignRole
  },
  data() {
    return {
      page: 1,
      size: 4,
      total: 0,
      list: [],
      loading: false,
      showDialog: false,
      showRoleDialog: false,
      userId: null
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    async getEmployeeList() {
      this.loading = true
      const { data: { rows, total }} = await reqGetEmployeeList(this.page, this.size)
      this.total = total
      this.list = rows
      this.loading = false
    },
    handleSizeChange(val) {
      this.size = val
      this.page = 1
      this.getEmployeeList()
    },
    handleCurrentChange(val) {
      this.page = val
      this.getEmployeeList()
    },
    indexMethod(index) {
      return (this.page - 1) * this.size + index + 1
    },
    formatEmployment(row, column, cellValue, index) {
      const obj = EmployeeEnum.hireType.find(item => item.id === +cellValue)
      return obj ? obj.value : '未知'
    },

    delEmployee(id) {
      this.$confirm('你确定删除该人吗', '温馨提示').then(async() => {
        await reqDelEmployee(id)
        if (this.list.length === 1 && this.page > 1) {
          this.page--
        }
        this.$message.success('删除成功')
        this.getEmployeeList()
      }).catch(() => {
        console.log('取消')
      })
    },
    async clickExport() {
      const { data: { rows }} = await reqGetEmployeeList(1, this.total)
      const headersArr = ['姓名', '手机号', '入职日期', '聘用形式', '转正日期', '工号', '部门']
      const headersRelations = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      const dataArr = this.formatJson(rows, headersArr, headersRelations)
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          header: headersArr,
          data: dataArr,
          filename: '员工名单',
          autoWidth: true,
          bookType: 'xlsx'
        })
      })
    },
    showRoleFn(id) {
      this.showRoleDialog = true
      this.userId = id
    },
    checkPermission(key) {
      if (this.$store.getters.roles) {
        return this.$store.getters.roles.points.includes(key)
      } else {
        return false
      }
    },
    formatJson(rows, headersArr, headersRelations) {
      const resultsArr = rows.map(item => {
        const arr = []
        headersArr.forEach(key => {
          const enlishKey = headersRelations[key]
          let value = item[enlishKey]
          if (['timeOfEntry', 'correctionTime'].includes(enlishKey)) {
            value = dayjs(value).format('YYYY-MM-DD')
          }
          if (enlishKey === 'formOfEmployment') {
            const obj = EmployeeEnum.hireType.find(obj => obj.id === +value)
            console.log(obj)
            console.log(value = obj)
            value = obj ? obj.value : '未知'
          }
          arr.push(value)
        })
        return arr
      })
      return resultsArr
    }
  }
}
</script>

<style>

</style>
